'use strict';

const RouterService = require('../base');

class DishService extends RouterService {
  static get modelName() {
    return 'Business.Dish';
  }

  // 批量创建菜品官方参考价格
  async batchCreate(payload) {
    const { monthly_bidding_id, dishes } = payload;
    // 查找供应商的报价记录时否存在supplierQuotes
    const supplierQuotes = await this.ctx.model.Business.SupplierQuote.findAll({
      where: {
        monthly_bidding_id,
        deleted: 0
      }
    });
    if (supplierQuotes.length > 0) {
      throw new Error('已导入供应商报价，不可再导入官方参考价格');
    }
    if (!monthly_bidding_id || !dishes || !Array.isArray(dishes)) {
      throw new Error('参数错误');
    }
    // 创建事务
    const transaction = await this.ctx.model.transaction();

    try {
      // 更新月度比较表的状态=2
      await this.ctx.model.Business.MonthlyBidding.update({
        status: 2
      }, {
        where: {
          id: monthly_bidding_id
        },
      });
      // 删除供应商报价
      await this.ctx.model.Business.SupplierQuote.destroy({
        where: {
          monthly_bidding_id,
          deleted: 0
        },
        transaction
      });
      // 更新所有供应商关联表的状态为1
      await this.ctx.model.Business.BiddingSupplier.update({
        status: 1
      }, {
        where: {
          monthly_bidding_id,
        }
      });
      // 先删除该比价项目的现有菜品数据
      await this.model.destroy({
        where: {
          monthly_bidding_id,
          deleted: 0
        },
        transaction
      });

      // 批量创建新的菜品数据
      const dishData = dishes.map(dish => ({
        name: dish.name,
        category: dish.category,
        unit: dish.unit,
        base_price: dish.base_price,
        monthly_bidding_id,
        status: 1
      }));

      await this.model.bulkCreate(dishData, { transaction });
      await transaction.commit();
    } catch (error) {
      await transaction.rollback();
      throw error;
    }
  }

  getListOrder() {
    return [
      ['category', 'ASC'],
    ]
  }

  async groupList({ key, category }) {
    if (!key) { 
      return []
    }
    let where = {}
    if (category) {
      where.category = category
    }
    // 根据category分组，将name相同的菜品合并，将菜品放到category的children中
    const dishes = await this.model.findAll({
      where: {
        deleted: 0,
        ...where
      },
      group: [key],
      attributes: [key]
    });
    return dishes
  }
}

module.exports = DishService;
